<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <title>按歌曲进度显示歌词</title>
</head>
<script type="text/javascript" src="lyrics.js"></script>

<body>
    <p class="time"></p>
    <p class="lyric"></p>
</body>
<script>
    const p = document.querySelector('p.lyric');
    const timeP = document.querySelector('p.time');
    // 间隔时间
    let intervalTime = 0
    // 每段歌词的开始时间
    let eachStartTime = Date.now()
    // 歌词索引
    let index = 0
    // 歌词之间的等待时间
    let waitTime = lyrics.length > 2 ? lyrics[index + 1].time - lyrics[index].time : null
    // 持续时长
    let duration = 0;
    // 歌词开始时间
    let startTime = Date.now();

    let count = 0

    function renderLyric() {

        // 最后一句歌词是时直接赋值
        if (index >= lyrics.length) {
    
            console.log(index);
            console.log('歌词已经结束');
            return
        }
        intervalTime = Date.now() - eachStartTime
        if (waitTime && intervalTime >= waitTime) {
            console.log(`索引${index} 等待时间${waitTime} 间隔时间${intervalTime}`);
            // 重置开始时间
            eachStartTime = Date.now()
            p.innerHTML = lyrics[index].content
            // 下一次等待时间
            if (index < lyrics.length - 1) {
                waitTime = lyrics[index + 1].time - lyrics[index].time
            } else {
                waitTime = null
            }

            index++
        }
        duration = Date.now() - startTime
        timeP.innerHTML = Duration(duration)
        requestAnimationFrame(renderLyric)
    }

    function Duration(duration) {
        duration = duration / 1000
        let mm = Math.trunc(duration / 60)
        let ss = Math.trunc(duration % 60)
        return ((Array(2).join('0') + mm).slice(-2)) + ':' + ((Array(2).join("0") + ss).slice(-2))
    }

    renderLyric()
</script>

</html>